<template>
   <div>
       <el-form :model="user" :rules="rules" ref="EditorUserForms"  >
               <el-form-item label="头像"   :label-width="formLabelWidth"  >
                 <el-upload class="avatar-uploader" :action="avatar1" :headers="{'Authorization': this.token }" :before-upload="beforeupload" :data="uploadParm" :show-file-list="false" :on-success="handleUpSuccess">
                 <img v-if="user.avatar" :src="user.avatar" class="avatar-24">
                 <i v-else class="el-icon-plus avatar-uploader-icon " style="width:80px;height:80px;"></i>
                 </el-upload>
               </el-form-item>

               <el-form-item label="用户名" prop="username" :label-width="formLabelWidth">
                <el-col :span="8"> <el-input v-model="user.username" ></el-input></el-col>
               </el-form-item>
               <el-form-item label="名称" prop="name" :label-width="formLabelWidth">
                <el-col :span="8">  <el-input v-model="user.name" placeholder="请输入名称">></el-input></el-col>
               </el-form-item>
               <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth">
                <el-col :span="8">  <el-input v-model="user.email" placeholder="请输入邮箱"></el-input></el-col>
               </el-form-item>
               <el-form-item label="用户角色" prop="role"  :label-width="formLabelWidth">
                <el-col :span="8">
                 <el-input v-model="role"  disabled></el-input>
                 </el-col>
               </el-form-item>

             </el-form>
       <div class="grid-content bg-purple">
           <el-button type="primary" @click="EditorUserClick('user')" >保存</el-button>
       </div>
   </div>
</template>

<script>
    export default {
        name: "UserDe",
        data() {
            /*****检验两次密码是否一致***/
            var validatePass = (rule, value, callback) => {
                if (value === "") {
                    callback(new Error("请输入密码"));
                } else {
                    if (this.ruleForm.checknewpass !== "") {
                        this.$refs.ruleForm.validateField("checknewpass");
                    }
                    callback();
                }
            };
            var validatePass2 = (rule, value, callback) => {
                if (value === "") {
                    callback(new Error("请再次输入密码"));
                } else if (value !== this.ruleForm.newpass) {
                    callback(new Error("两次输入密码不一致!"));
                } else {
                    callback();
                }
            };
            var validateUserName = (rule, value, callback) => {
                var reg_username = /^\w{6,12}$/;
                var flag = reg_username.test(value)
                if (!value) {
                    return callback(new Error('用户名不能为空'));
                }
                else if(!flag){
                    return callback(new Error('用户名长度为6-12位'))
                }
                else callback();
            };
            var validateName = (rule, value, callback) => {
                var reg_username = /^^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]{1,12}$/;
                var flag = reg_username.test(value)
                if (!value) {
                    return callback(new Error('昵称不能为空'));
                }
                else if(!flag){
                    return callback(new Error('昵称长度不能超过12位'))
                }
                else callback();
            };
            return {
                uploadParm: {}, //图片的上传
                loading: true,
                baseUrl: '/avatar/',
                user: {},//用户信息表单
                formLabelWidth: "150px",
                username:"",
                role:"",
                imageUrl: '',
                avatar: '',
                avatar1:"http://localhost:8081/user/uploadAvatar",
                token:localStorage.getItem("token"),
                userList:[],
                rules: {


                    pass: [
                        {
                            required: true,
                            trigger: "blur",
                            message: "请输入密码"
                        }
                    ],
                    newpass: [
                        {
                            validator: validatePass,
                            trigger: "blur"
                        }
                    ],
                    checknewpass: [
                        {
                            validator: validatePass2,
                            trigger: "blur"
                        }
                    ],
                    username: [
                        {
                            validator: validateUserName,
                            trigger: "blur"
                        }
                    ],
                    name: [
                        {
                            validator: validateName,
                            trigger: "blur"
                        }
                    ],
                    email: [
                        {
                            required: true,
                            message: "请输入电子邮箱"
                        },
                        {
                            pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/,
                            message: "请输入有效的邮箱"
                        }
                    ],
                }
            };
        },
        created() {
            this.getUser();


        },

        methods: {



            //获取个人用户的信息
            getUser() {

                if (this.$store.getters.getUser.username) {

                    this.username = this.$store.getters.getUser.username
                }

                this.$axios.get('/user/getUserDetail?username=' + this.username, {
                    headers: {
                        "Authorization": localStorage.getItem("token")
                    }
                }).then(res => {


                    this.user = res.data.data;
                    if(this.user.status=='1'){
                        this.role='管理员'
                    }else {
                        this.role='用户'
                    }

                });
            },

            beforeupload(file) {


                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            //图片上传上传成功
            handleUpSuccess(response, file) {

                var obj = {
                    username: this.username,
                    avatarname: response.data
                };

                this.$axios.post('/user/alterAvatar',obj,{headers:{
                        "Authorization": localStorage.getItem("token")
                    }}).then(res=>{

                    console.log(res);
                })
                var obj1 = {
                    id: this.user.id,
                    username: this.user.username,
                    avatar: response.data,
                    name: this.user.name
                };

                this.user.avatar = this.avatar;
                this.$store.commit("SET_USERINFO",obj1);
                location.reload()
                
            },
            // 编辑提交的方法
            EditorUserClick() {
                this.$refs.EditorUserForms.validate(valid => {
                    if (valid) {


                        this.$axios.post("/user/alterUser", this.user, {
                            headers: {
                                "Authorization": localStorage.getItem("token")
                            }
                        }).then(response => {
                            if (response.status == 200) {
                                this.$message({
                                    message: "编辑成功",
                                    type: "success"
                                });
                            } else {
                                this.$message({
                                    message: "修改失败" + response.message,
                                    type: "error"
                                });
                            }
                        });
                    }
                });
            }
        }
    }
</script>

<style scoped>
    .el-table{

    }
    .avatar-24 {
        width: 50px;
        height: 50px;
        border-radius: 50%;
    }
    .all-container-paddingbg{
        width: 1200px;
        overflow: hidden;
        margin: 0 auto;
    }
</style>